package com.bolingcavalry.crm.security.config;

import com.base.RoleEnum;
import com.bolingcavalry.crm.security.CustomAccessDeniedHandler;
import com.bolingcavalry.crm.user.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;


import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private CustomAccessDeniedHandler customAccessDeniedHandler;
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .cors().and() // 启用 CORS
                .csrf().disable()
            // 禁用 CSRF 保护（适用于 REST API）
            .csrf().disable()
            // 禁用 Session
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            // 配置权限规则
            .authorizeRequests()
                // 配置spring security允许所有人访问登录接口，可以在url之后拼接url就可以增加访问的权限
                .antMatchers("/auth/**", "/auth/registered","/**/download-excel/**","/aftersales/count").permitAll()
                .antMatchers("/auth/me").authenticated()
                // 需要角色，在url之后拼接url就可以增加访问的权限，在tokenutils生成的token中包含了角色信息，hasRole会拿到这其中的角色信息
                .antMatchers("/admin/**").hasRole(RoleEnum.ADMIN.getCode())
                .antMatchers("/user/**").hasAnyRole("USER", "ADMIN")
                //.antMatchers("/**/updateStatus").hasAnyRole( "ADMIN", "leader", "department_leader", "production_leader", "technical_command", "mc_leader", "instrument_leader", "general_leader", "general_command", "sales_leader","sales_department")
                .antMatchers("/aftersales/add","/serviceorder/add").hasAnyRole("ADMIN", "leader", "department_leader", "production_leader", "technical_command", "mc_leader", "instrument_leader", "general_leader", "general_command", "sales_leader","sales_department")
                .anyRequest().authenticated() // 其他请求需要认证
                .and()
                .exceptionHandling()
                .authenticationEntryPoint((request, response, authException) -> {
                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    response.setContentType("application/json");
                    response.getWriter().write("{\"code\":401,\"message\":\"Unauthorized\"}");
                })
                .accessDeniedHandler(customAccessDeniedHandler) // 设置自定义拒绝处理器
                .and()
            // 添加 JWT 验证过滤器
            .addFilterBefore(new JwtTokenFilter(jwtUtil), UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }


    // 在类中添加如下 Bean：
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOriginPatterns(Arrays.asList("*")); // 允许所有来源（生产环境应限制具体域名）
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

}